export default class util{
	static getValueByKey(data, key) {
		for(var i = 0; i < data.length; i++) {
			var item = data[i];
			if(item.key == key) {
				return item.value;
			}
		}
	}
	static getKeyByValue(data, key) {
		for(var i = 0; i < data.length; i++) {
			var item = data[i];
			if(item.value == key) {
				return item.key;
			}
		}
	}
	static getCookie(cookieVal) {
		/**
		 * 获取cookie的值
		 * cookieVal 参数是cookie中的key返回value
		 * @type {string}
		 */
		var currentCookie = "";
		document.cookie.split(";").forEach((item) => {
			if(this.trim(item.split("=")[0]) === cookieVal) {
				currentCookie = item.split("=")[1] || "";
			}
		});
		return currentCookie;
	}
	static getUrlKey(name) {
		/*
		 * 获取 URL 后面拼接的参数数据
		 *
		 * 调用方式
		 * let token = YHUtility.getUrlKey('token');
		 *
		 * 通过路由的方式（拓展）
		 * 地址：http://localhost:3333/#/index?id=001
		 * console.log(this.$route.query.id)
		 * 结果：001
		 * */
		return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ""])[1].replace(/\+/g, '%20')) || null
	}
	static getCurrTime(ops='-'){
	  let y = (new Date()).getFullYear();
	  let m =(new Date()).getMonth()+1;
	  let d = (new Date()).getDate();
	  let h = (new Date).getHours();
	  let min = (new Date).getMinutes();
	  let s = (new Date).getSeconds();
	  return{
      YMD:y+ops+m+ops+d,
      YM:y+ops+m,
      MD:m+ops+d,
      HMin:h+':'+min,
      HMinS:h+':'+min+':'+s,
      YMDHMin:y+ops+m+ops+d + ' '+h+':'+min
    }
  }
	static getTimeStamp(time) {
		/*
		 * 获取时间戳
		 * @param time
		 * @returns {number}
		 * */
		return new Date(time.replace(/-/g, "/")).getTime();
	}
	static imeDifferencet(starDateTime, endDateTime) {
		/*
		 * 时间差
		 * @param startDateTime
		 * @param endDateTime
		 * @returns {string}
		 * @constructor
		 * */
		let dataTime = endDateTime - starDateTime;
		let hours = dataTime / (3600 * 1000);
		return hours.toFixed(1);
	}
	static formatDate(time, type, format) {
		/*
		 * @param time
		 * @param type (默认'yyyy-MM-dd HH:mm')
		 * @param format
		 * */
		var date = "";
		if(format) {
			date = time;
		} else {
			if(typeof time !== "number") {
				time = time.replace(/-/g, "/");
			}
			date = new Date(time);
		}

		type = type ? type : "yyyy-MM-dd HH:mm";

		var seperator1 = "-";
		var seperator2 = ":";
		var month = (date.getMonth() + 1).toString();
		var day = date.getDate().toString();
		var hours = date.getHours().toString();
		var minutes = date.getMinutes().toString();
		var seconds = date.getSeconds().toString();

		month = month.length === 1 ? ("0" + month) : month;
		day = day.length === 1 ? ("0" + day) : day;
		hours = hours.length === 1 ? ("0" + hours) : hours;
		minutes = minutes.length === 1 ? ("0" + minutes) : minutes;
		seconds = seconds.length === 1 ? ("0" + seconds) : seconds;

		if(type === "yyyy-MM-dd HH:mm:ss") {
			return date.getFullYear() + seperator1 + month + seperator1 + day + " " + hours + seperator2 + minutes + seperator2 + seconds;
		} else if(type === "yyyy-MM-dd HH:mm") {
			return date.getFullYear() + seperator1 + month + seperator1 + day + " " + hours + seperator2 + minutes;
		} else if(type === "yyyy-MM-dd") {
			return date.getFullYear() + seperator1 + month + seperator1 + day;
		} else if(type === "yyyy-MM") {
			return date.getFullYear() + seperator1 + month;
		} else if(type === "HH:mm") {
			return hours + seperator2 + minutes;
		}
	}
	static trim(text) {
		/*去除首位空格*/
		return text == null ? "" : (text + "").replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "");
	}
	/**
	 * 判断是否为空
	 */
	static isEmpty(str) {
		if(str == null || str.length == 0 || str === '' || str === 'undefined'){
			return true;
		}
		return false;
	}
	static checkSuffix(fileName) {
		/*
		 * 校验图片真伪
		 * @param fileName
		 * @returns {boolean}
		 * */
		const imgSuffixs = ["jpg", "jpeg", "png", "bmp", "gif"];
		const index = fileName.lastIndexOf(".");
		const suffix = fileName.substr(index + 1).toLowerCase();

		if(suffix) {
			return imgSuffixs.includes(suffix);
		} else {
			return false;
		}
	}
	static goBackView(that, cacheState) {
		/*返回上一页*/
		that.$route.meta.keepAlive = cacheState; // 用于上一页缓存(true & false)
		// that.$route.back(-1);
		that.$route.go(-1);
	}
	static fastSort(arr, fn) {
		/*
		 * 快速排序
		 * @param arr
		 * @param fn
		 * @returns {*[]}
		 * */
		let center = arr[0];
		let len = arr.length;
		let left = [];
		let right = [];
		let i = 1;

		for(; i < len; i++) {
			if(fn(center, arr[i])) {
				left.push(arr[i]);
			} else {
				right.push(arr[i]);
			}
		}

		if(1 < left.length) {
			left = this.fastSort(left, fn);
		}

		if(1 < right.length) {
			right = this.fastSort(right, fn);
		}

		return left.concat(center, right);
	}
	static pickerType(type, value) {
		switch(type) {
			case "year":
				return `${value}年`;
			case "month":
				return `${value}月`;
			case "day":
				return `${value}日`;
			case "hour":
				return `${value}时`;
			case "minute":
				return `${value}分`;
		}
		return value;
	}

  /**
   * 从一个数组中随机取出一个元素
   * @param {Array} arr 原数组
   * @param num
   **/
  static getRandomArrayElement = (arr,num=arr.length/2) => {
    let newArr = [];
    for(let i=0;i<num;i++){
      newArr.push(arr[Math.floor(Math.random() * arr.length)])
    }
    newArr = Array.from(new Set(newArr));
    return newArr;
  };
  static formatTime = (date) => {
    function formatNumber(n) {
      n = n.toString()
      return n[1] ? n : '0' + n
    }
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var hour = date.getHours();
    var minute = date.getMinutes();
    var second = date.getSeconds();
    return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
  }
}
